import { JwtService } from '@nestjs/jwt'
import { Injectable } from '@nestjs/common'
import { CacheKey, ForceLogoutDTO } from '@/common'
import { RedisService } from '@/shared/redis.service'
import { SharedService } from '@/shared/shared.service'

@Injectable()
export class OnlineService {
  constructor(private readonly redisService: RedisService, private readonly jwtService: JwtService, private readonly sharedService: SharedService) {}

  /**分页列表查询 */
  public async findList(queryParams: TableQueryParams<{ address: string; username: string }>) {
    const { take = 10, skip = 0, username = '', address = '' } = queryParams
    // 获取所有匹配的 token 键
    const tokenKeyList = await this.redisService.keys(`${CacheKey.ADMIN_USER_TOKEN}:*`)
    const userIds = tokenKeyList.map((item) => item.replace(`${CacheKey.ADMIN_USER_TOKEN}:`, ''))
    // 计算总记录数（在过滤前）
    const total = userIds.length
    // 计算需要获取的页数
    const totalPages = Math.ceil(total / take)
    const currentPage = Math.floor(skip / take) + 1
    // 如果请求的页数超出范围，直接返回空结果
    if (currentPage > totalPages) return { total, records: [] }
    // 批量获取用户在线数据（按分页偏移量）
    const paginatedUserIds = userIds.slice(skip, skip + take)
    // 并行获取当前页的数据（性能优化）
    const recordPromises = paginatedUserIds.map((userId) => this.redisService.get(`${CacheKey.ADMIN_USER_ONLINE}:${userId}`))
    let temps = await Promise.all(recordPromises)
    let records: Recordable[] = temps.map((item) => JSON.parse(item!))
    if (username || address) records = records.filter((item) => item.includes(username) && item.includes(address))
    return { total, records }
  }

  /** 强制用户退出登录，清除与该用户相关的所有 Redis 缓存 */
  public async forceLogout(data: ForceLogoutDTO) {
    const keys = await this.redisService.keys(`*${data.userId}*`)
    if (!keys.length) return '未发现需要清除的用户缓存'
    await this.redisService.del(keys)
    return '强退成功'
  }
}
